package com.github.ecbp.common.security.filter;

import com.github.ecbp.common.constant.CacheKeyConstant;
import com.github.ecbp.common.security.utils.CommonAdminUtils;
import com.github.ecbp.common.security.utils.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PathMatcher;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 动态权限决策管理器，用于判断用户是否有访问权限
 */
public class DynamicAccessDecisionManager implements AccessDecisionManager {
    private static final Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        List<String> needAuthorities = configAttributes.stream().map(ConfigAttribute::getAttribute).collect(Collectors.toList());
        // 获得所有的匹配的路由权限配置, 未设置操作请求权限，返回空集合
        if (CollectionUtils.isEmpty(needAuthorities) || needAuthorities.get(0).equals(JwtTokenUtil.NO_CONFIG_URL)) {
            throw new AccessDeniedException("接口未配置访问权限");
        }

        PathMatcher pathMatcher = new AntPathMatcher(CacheKeyConstant.PATH_SEPARATOR);
        //将访问所需资源或用户拥有资源进行比对
        for (String needAuthority : needAuthorities) {
            for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
                if (pathMatcher.match(grantedAuthority.getAuthority(), needAuthority.trim())) {
                    LOGGER.info("[ 权限验证通过: {} ]", grantedAuthority.getAuthority());
                    return;
                }
            }
        }

        LOGGER.info("[ 权限验证失败, 用户'{}'没有访问权限: {} ]", CommonAdminUtils.getLoginPhoneFromToken(), needAuthorities);
        throw new AccessDeniedException("抱歉，您没有访问权限");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

}